<!-- excel导出弹窗层 -->
<template>
  <el-dialog
    :title="$t('msg.excel.title')"
    :model-value="modelValue"
    @close="closed"
    width="30%"
  >
  <el-input v-model="excelName" :placeholder="$t('msg.excel.placeholder')"></el-input>

  <template #footer>
    <div class="dialog-footer">
      <el-button @click="closed">{{ $t('msg.excel.close') }}</el-button>
      <el-button type="primary" @click="onConfirm" :loading="loading">{{ $t('msg.excel.confirm') }}</el-button>
    </div>
  </template>

  </el-dialog>
</template>

<script setup>
import { defineProps, defineEmits, ref } from 'vue'
import { useI18n } from 'vue-i18n'
import { watchSwitchLang } from '@/utils/i18n'
import { getUserManageAllList } from '@/api/user-manage'
import { USER_RELATIONS } from './ExportToExcelConstants'
import { dateFilter } from '@/filters'
import { ElMessage } from 'element-plus'

defineProps({
  modelValue: {
    type: Boolean,
    required: true
  }
})

// 处理导出文件语言
const i18n = useI18n()
let exportDefaultName = i18n.t('msg.excel.defaultName')
const excelName = ref('')
excelName.value = exportDefaultName
watchSwitchLang(() => {
  exportDefaultName = i18n.t('msg.excel.defaultName')
  excelName.value = exportDefaultName
})

// 点击确定按钮
const loading = ref(false)
const onConfirm = async () => {
  loading.value = true

  // 数据
  const allUser = (await getUserManageAllList().catch(() => {
    ElMessage.error('请重试')
    loading.value = false
  })).list

  // 导入工具包
  const excel = await import('@/utils/Export2Excel')

  const data = formatJson(USER_RELATIONS, allUser)
  excel.export_json_to_excel({
    // excel 表头
    header: Object.keys(USER_RELATIONS),
    // excel 数据
    data,
    // 文件名称
    filename: excelName.value || exportDefaultName
  })
  closed()
}

// 该方法负责将数组转化成 Excel能够识别的二维数组
const formatJson = (headers, rows) => {
  return rows.map(item => {
    return Object.keys(headers).map(key => {
      // 角色需要进行特殊处理
      if (headers[key] === 'role') {
        const roles = item[headers[key]]
        return roles[0].title
      }
      // 处理时间问题
      if (headers[key] === 'openTime') {
        return dateFilter(item[headers[key]])
      }
      return item[headers[key]]
    })
  })
}

// 关闭事件
const emits = defineEmits(['update:modelValue'])
const closed = () => {
  emits('update:modelValue', false)
  loading.value = false
}

</script>
<style lang="scss" scoped>
</style>
